class Transaction

  attr_reader :total_debits, :total_credits, :entries, :date
  
  def initialize(date)
    @date = date
    @entries = []
    @observers = []
    @total_debits = 0
    @total_credits = 0
  end
  
  def add_credit(account, amount)
    @entries << {
      :tx_type => :credit,
      :account => account,
      :amount => amount
    }
    @total_credits += amount
  end
  
  def add_debit(account, amount)
    @entries << {
      :tx_type => :debit,
      :account => account,
      :amount => amount
    }
    @total_debits += amount
  end
  
  def adjust_entry(index, amount)
    prev = @entries[index][:amount]
    @entries[index][:amount] = amount
    if(:debit == @entries[index][:tx_type])
      @total_debits -= prev 
      @total_debits += amount
      notify(@entries[index][:account], amount, prev)
    else
      @total_credits -= prev 
      @total_credits += amount
      notify(@entries[index][:account], prev, amount)
    end
  end

  def is_balanced?
    return total_debits == total_credits
  end

  def notify(account, debit, credit)
    @observers.each{|o| o.call(account, debit, credit) }
  end
 
  def remove_entry(index)
    rem = @entries.slice!(index)
    if(:debit == rem[:tx_type])
      @total_debits -= rem[:amount] 
      notify(rem[:account], 0, rem[:amount])
    else
      @total_credits -= rem[:amount]
      notify(rem[:account], rem[:amount], 0)
    end
  end

  def watch(&block)
    @observers << block
  end
end

  